#include "systick.h"
#include "config.h"

uint32 sysTimer[MAX_TIMER];  //软件定时器数目
uint32 TaskTimer[TaskNum];  //定义任务定时器数目


static uint32 g_iRunTimer = 0; //定义系统全局运行时间

void SysTickInit(void)//滴答定时器初始化
{
	uchar i;
	for(i = 0; i < MAX_TIMER; i++)
	sysTimer[i] = 0;
	
	for(i = 0; i < TaskNum; i++)
	TaskTimer[i] = 0;
	
	SysTick_Config(72000000/1000);//每隔1ms进一次系统滴答中断响应函数，主频72M
}
//中断处理
void SysTick_Handler(void)
{
	uint8 i;
	for(i = 0; i < MAX_TIMER; i++)
	if(sysTimer[i]) 
		sysTimer[i]--;
	
	for(i = 0; i < TaskNum; i++)
	if(TaskTimer[i]) 
		TaskTimer[i]--;
	
	if(g_iRunTimer++ == 0xFFFFFFFF) 
		g_iRunTimer = 0;
}

void SysTickDelayms(uint32 nms)
{
	CPU_INT_ENABLE();
	DelayTimer = nms ;
	while(DelayTimer);
	
}

void SysTickDelayUs(uint32 nus) //注意该函数延时不能超过1ms  视频17
{
    uint32 delta;

    /* 获得延时经过的tick数 */
    nus = nus * (SysTick->LOAD/(1000000/1000));

    /* 获得当前时间 */
    delta = SysTick->VAL;

    /* 循环获得当前时间，直到达到指定的时间后退出循环 */
    while (delta - SysTick->VAL< nus);
}


uint32 GetRunTime(void)//获取系统时间
{
	uint32 RunTime;
	CPU_INT_DISABLE();
	
	RunTime = g_iRunTimer;
	
	CPU_INT_ENABLE();
	
	return RunTime;

}
